﻿using System.IO;
using CVBanc.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Web;
using System.Web.Mvc;
using System.Linq;
using System.Web.Script.Serialization;

namespace CVBanc.Controllers
{
    public class OperationController : Controller 
    {
        //
        // GET: /Operation/

        public ActionResult Index()
        {
            var user = CheckAuthentification((string)Session["username"], (string)Session["password"]) ; 
            if (user == null)
                return HttpNotFound();
            ViewData["name"] = user.Firstname+" "+user.Lastname ; 
            return View();
        }
        private User CheckAuthentification(string username, string password)
        {


            using (var db = new Context())
            {
                var user = db.Users.Where(x => x.Username == username && x.Password == password).FirstOrDefault();
                if (user != null)
                    return user;
                else
                    return null;

            }

        }
       [HttpPost]
        public string Upload()
        {
            // variable
            var messege = string.Empty; 

            try
            {
                
                //get file 
                var file = Request.Files["file"];
                var stream = file.InputStream;
                var length = (int)stream.Length;
                byte[] file_byte = new byte[length];
                stream.Read(file_byte, 0, length);


                //get Keywords
                var keywords = Request["keywords"].Trim();
                
                var id = Session["id"];

                using (var db = new Context())
                {
                    var user = db.Users.SingleOrDefault(x => x.Id == (int)id);

                    if (file_byte.Length != 0)
                        //if(user.File == null)
                        //    user.File = new byte[length];  
                     user.File = file_byte;
                    if(keywords!="")
                        user.Keywords = keywords;

                   // db.Users.Add(user);
                    //db.Users.Attach(user);

                    db.SaveChanges();
                  //  var usertest = db.Users.SingleOrDefault(x => x.Id == (int)id);

                }
                messege = "Enregistré" ; 
                return messege ; 
            }
            catch (Exception e)
            {
                messege = "Erreur de sauvegarde"; 
                return messege; 
            
            }

        }
        [HttpPost]
       public JsonResult Search()
       //public string Search()
       {
          try{

           var jr = new JsonResult(); 
           var eng = Request["engineering"];
           var kw = Request["keywords"];
           var users = new List<User>();
           if (kw == "")
           {
               using (var db = new Context())
               {
                    users = db.Users.Where(m => m.Engineering == eng && m.File !=null).ToList();
               }
           }
           else
           {
               var keywords = Request["keywords"].Split(';');

               using (var db = new Context())
               {
                   foreach (var keyw in keywords)
                   {

                       var us = db.Users.Where(m => m.Keywords.Contains(keyw) && m.Engineering == eng && m.File != null).ToList();
                       if (us != null)
                           users.AddRange(us);
                   }

               }
           }
           if (users.Count == 0)
           {
               //throw new Exception();
               
               jr.Data = null; 
               
               return jr ; 
           }
               var distUsers = users.Distinct();
               var userDTOList = new List<UserDTO>();

               foreach (var i in distUsers)
               {
                   var dto = new UserDTO();
                   dto.Firstname = i.Firstname;
                   dto.Lastname = i.Lastname;
                   dto.Id = i.Id;

                   userDTOList.Add(dto);
               }

               var jsonSerialiser = new JavaScriptSerializer();
               var json = jsonSerialiser.Serialize(userDTOList);

              
               jr.Data = json;
               return jr;
               //return json;
           }
           //else return null; 
              catch(Exception e)
            {
             return  new JsonResult() { Data = e}; 
              //return e.Message; 

              }
       }
        //public ActionResult LoadFile(int id)
        [HttpGet]
        //public ActionResult LoadFile(string id)
        public ActionResult LoadFile(int id)
        {
            using (var db = new Context())
            {
                var binaryFile  = db.Users.SingleOrDefault(x => x.Id == id).File;
                return File(binaryFile, "Application/pdf", "cv"); 
            
            } 
           
        }

    }
    public class UserDTO
    {
        public string Lastname { get; set; }
        public string Firstname { get; set; }
        public int Id { get; set; }
    }
    
}
